#pragma once 

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "TcpServer.hpp"
#include "Protocols.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
  private:
    int port;
    bool stop;
  public:
    HttpServer(int _port = PORT)
      :port(_port),stop(false) //不能停止
    {}
    
    void InitServer()
    {
      //信号SIGPIPE需要进行忽略，如果不忽略在写入时可能直接崩溃
      signal(SIGPIPE , SIG_IGN);
    }
    
    void Loop()
    {
      TcpServer* tsvr = TcpServer::getinstance(port);
      LOG(INFO , "Loop begin");
      while (!stop)
      {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        //接收tcp发送的连接请求
        int sock = accept(tsvr->Sock() , (struct sockaddr*)&peer , &len);
        if (sock < 0) 
        {
          continue;
        }
        LOG(INFO , "Get a new link");        
        Task task(sock); //构建一个任务
        ThreadPool::getinstance()->PushTask(task); //将任务插入到任务队列中
      }
    }

    ~HttpServer()
    {}
};
